function addRow() {
    const tbody = document.querySelector('#shipTable tbody');
    const row = document.createElement('tr');
    
    // Add checkbox column
    row.innerHTML = `<td><input type="checkbox"></td>`;
    
    // Add data cells
    const columns = 27; // Updated number of data columns
    for (let i = 0; i < columns; i++) {
        row.innerHTML += `<td contenteditable="true"></td>`;
    }
    
    tbody.appendChild(row);
}

function deleteSelectedRows() {
    const tbody = document.querySelector('#shipTable tbody');
    const checkboxes = tbody.querySelectorAll('input[type="checkbox"]:checked');
    
    checkboxes.forEach(checkbox => {
        checkbox.closest('tr').remove();
    });
}

function toggleAllRows(checkbox) {
    const tbody = document.querySelector('#shipTable tbody');
    const checkboxes = tbody.querySelectorAll('input[type="checkbox"]');
    
    checkboxes.forEach(cb => {
        cb.checked = checkbox.checked;
    });
}

// Add an initial empty row when the page loads
document.addEventListener('DOMContentLoaded', () => {
    addRow();
});

function generateRandomShipData() {
    const shipNames = ['COSCO SHIPPING', 'MAERSK LINE', 'MSC OSCAR', 'EVER GIVEN', 'CMA CGM'];
    const destinations = ['Shanghai', 'Singapore', 'Rotterdam', 'Hong Kong', 'Busan'];
    const aisTypes = ['Class A', 'Class B'];
    
    // 渤海湾中心区域范围
    const LAT_MIN = 37.5;  // 渤海南部纬度
    const LAT_MAX = 40.5;  // 渤海北部纬度
    const LON_MIN = 118.5; // 渤海西部经度
    const LON_MAX = 121.0; // 渤海东部经度
    
    return {
        targetId: Math.floor(Math.random() * 1000000),  // 添加targetId
        name: shipNames[Math.floor(Math.random() * shipNames.length)],
        mmsi: Math.floor(Math.random() * 900000000 + 100000000),
        state: Math.floor(Math.random() * 15),
        rotation: Math.floor(Math.random() * 360),
        imo: Math.floor(Math.random() * 9000000 + 1000000),
        call: 'CALL' + Math.floor(Math.random() * 9999),
        speed: (Math.random() * 40).toFixed(1),  // 0-40节速度
        center_lat: (Math.random() * (LAT_MAX - LAT_MIN) + LAT_MIN).toFixed(6),
        center_lon: (Math.random() * (LON_MAX - LON_MIN) + LON_MIN).toFixed(6),
        course_ship: Math.floor(Math.random() * 360),
        course_land: Math.floor(Math.random() * 360),
        length: Math.floor(Math.random() * 300 + 100),
        width: Math.floor(Math.random() * 50 + 10),
        shiptype: Math.floor(Math.random() * 100),
        ETA: new Date(Date.now() + Math.random() * 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
        draft: (Math.random() * 20).toFixed(1),
        aistype: aisTypes[Math.floor(Math.random() * aisTypes.length)],
        dest: destinations[Math.floor(Math.random() * destinations.length)],
        icontype: Math.floor(Math.random() * 10),
        settype: Math.floor(Math.random() * 5),
        unixtime: Date.now(),
        anchor_lat: (Math.random() * 180 - 90).toFixed(6),
        anchor_lon: (Math.random() * 360 - 180).toFixed(6),
        anchor_unixtime: Date.now() - Math.floor(Math.random() * 86400000),
        radar_id: Math.floor(Math.random() * 1000),
        radar_speed: (Math.random() * 30).toFixed(1),
        radar_course: Math.floor(Math.random() * 360)
    };
}

function addSimulatedShip() {
    const tbody = document.querySelector('#shipTable tbody');
    const row = document.createElement('tr');
    const shipData = generateRandomShipData();
    
    // Add checkbox column
    row.innerHTML = `<td><input type="checkbox"></td>`;
    
    // Add ship data cells
    Object.values(shipData).forEach(value => {
        row.innerHTML += `<td contenteditable="true">${value}</td>`;
    });
    
    tbody.appendChild(row);
}

// 添加船舶运动状态存储
const shipStates = new Map();

// 生成随机变化值，确保变化平滑
function generateSmallChange() {
    return (Math.random() - 0.5) * 2; // 增加到-1到1之间的变化
}

// 专门用于航向的变化生成
function generateCourseChange() {
    return (Math.random() - 0.5) * 5; // 航向每次可变化-2.5到2.5度
}

// 更新单个船舶数据
function updateShipPosition(row) {
    const cells = row.cells;
    const mmsi = cells[3].textContent; // 调整MMSI索引
    
    // 获取或初始化船舶状态
    if (!shipStates.has(mmsi)) {
        shipStates.set(mmsi, {
            speedTrend: generateSmallChange(),
            courseTrend: generateCourseChange(),
            lastUpdate: Date.now()
        });
    }
    
    const state = shipStates.get(mmsi);
    const currentTime = Date.now();
    const deltaTime = (currentTime - state.lastUpdate) / 1000; // 转换为秒
    state.lastUpdate = currentTime;

    // 更新速度（调整列索引）
    let speed = parseFloat(cells[8].textContent);
    speed += state.speedTrend;
    if (speed < 0) speed = 0;  // 最小速度0节
    if (speed > 40) speed = 40;  // 最大速度40节
    cells[8].textContent = speed.toFixed(1);

    // 更新航向（调整列索引）
    let course = parseFloat(cells[11].textContent);
    course += state.courseTrend;
    if (course >= 360) course -= 360;
    if (course < 0) course += 360;
    cells[11].textContent = Math.round(course);

    // 更新位置（调整列索引）
    let lat = parseFloat(cells[9].textContent);
    let lon = parseFloat(cells[10].textContent);
    
    // 根据速度和航向计算位置变化
    const distanceNm = speed * deltaTime / 3600; // 将小时速度转换为实际移动距离（海里）
    const latChange = distanceNm * Math.cos(course * Math.PI / 180) / 60;
    const lonChange = distanceNm * Math.sin(course * Math.PI / 180) / (60 * Math.cos(lat * Math.PI / 180));
    
    lat += latChange;
    lon += lonChange;
    
    // 确保经纬度在有效范围内
    lat = Math.max(-90, Math.min(90, lat));
    lon = Math.max(-180, Math.min(180, lon));
    
    cells[9].textContent = lat.toFixed(6);
    cells[10].textContent = lon.toFixed(6);

    // 随机更新趋势
    if (Math.random() < 0.2) { // 增加到20%的概率改变趋势
        state.speedTrend = generateSmallChange();
        state.courseTrend = generateCourseChange(); // 使用专门的航向变化函数
    }
}

// 获取所有船舶数据
function getAllShipsData() {
    const tbody = document.querySelector('#shipTable tbody');
    const rows = Array.from(tbody.getElementsByTagName('tr'));
    return rows.map(row => {
        const cells = row.cells;
        return {
            targetId: parseInt(cells[1].textContent),
            name: cells[2].textContent,
            mmsi: cells[3].textContent,
            state: parseInt(cells[4].textContent),
            rotation: parseInt(cells[5].textContent),
            imo: parseInt(cells[6].textContent),
            call: cells[7].textContent,
            speed: parseFloat(cells[8].textContent),
            center_lat: parseFloat(cells[9].textContent),
            center_lon: parseFloat(cells[10].textContent),
            course_ship: parseFloat(cells[11].textContent),
            course_land: parseFloat(cells[12].textContent),
            length: parseFloat(cells[13].textContent),
            width: parseFloat(cells[14].textContent),
            shiptype: parseInt(cells[15].textContent),
            ETA: cells[16].textContent,
            draft: parseFloat(cells[17].textContent),
            aistype: cells[18].textContent,
            dest: cells[19].textContent,
            icontype: parseInt(cells[20].textContent),
            settype: parseInt(cells[21].textContent),
            unixtime: parseInt(cells[22].textContent),
            anchor_lat: parseFloat(cells[23].textContent),
            anchor_lon: parseFloat(cells[24].textContent),
            anchor_unixtime: parseInt(cells[25].textContent),
            radar_id: parseInt(cells[26].textContent),
            radar_speed: parseFloat(cells[27].textContent),
            radar_course: parseFloat(cells[28].textContent)
        };
    });
}

// 发送船舶数据到服务器
async function sendShipsDataToServer() {
    try {
        const ships = getAllShipsData();
        await fetch('/update-ships', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ ships })
        });
    } catch (error) {
        console.error('Error sending ships data:', error);
    }
}

// 更新所有船舶位置
function updateAllShips() {
    const tbody = document.querySelector('#shipTable tbody');
    const rows = tbody.getElementsByTagName('tr');
    for (let row of rows) {
        updateShipPosition(row);
    }
    // 每次更新位置后发送数据到服务器
    sendShipsDataToServer();
}

let simulationInterval = null;

function toggleSimulation() {
    const button = document.getElementById('simulationButton');
    const status = document.getElementById('simulationStatus');
    
    if (simulationInterval === null) {
        // Start simulation
        simulationInterval = setInterval(updateAllShips, 1000); // 每秒更新一次
        button.textContent = 'Stop Simulation';
        button.style.backgroundColor = '#dc3545';
        status.textContent = 'Status: Running';
    } else {
        // Stop simulation
        clearInterval(simulationInterval);
        simulationInterval = null;
        button.textContent = 'Start Simulation';
        button.style.backgroundColor = '#007bff';
        status.textContent = 'Status: Stopped';
        shipStates.clear(); // 清除所有状态
    }
}
